<template>
  <div>
    <cus-allcard :showTitle="false">

      <div style="padding-top:24px">
      <div style="display: flex; justify-content: end" class="mb_20">
        <cus-button @onClick="batchAccounting">批量入账</cus-button>
      </div>
 
        <cusTable border
               :loading="form.loading"
               :columns="columns"
               :data="dataList"
               :customHeight="202"
               :size="vuex_config.tableSize"
               :bottomClass="['cus-page']"
               @on-selection-change ="selectionChange"
               >
          <template slot-scope="{ row }"
                    slot="createtime">
            {{new Date(row.createtime).Format('yyyy-MM-dd hh:mm:ss')}}
          </template>
          <template slot-scope="{ row }"
                    slot="money">
            {{totalPrices(Number(row.money))}}
          </template>
          <template slot-scope="{ row }"
                    slot="operationBz">
            <div class="flex">
              <cus-button type="text"
                          size="small"
                          style="color:#1E6FFF;padding:0 8px;"
                          @onClick="selectModelChange(row.remark)">
                <Icon type="ios-search"
                      style="font-size: 15px;"></Icon>查看
              </cus-button>
            </div>
          </template>
          <template slot-scope="{ row }"
                    slot="operationYspz">
            <div class="flex">
              <cus-button type="text"
                          size="small"
                          style="color:#1E6FFF;padding:0 8px;"
                          @onClick="tableIsHandoverButtton(row)">

                <Icon type="ios-cloud-download-outline"
                      style="font-size: 15px;"></Icon>导出
              </cus-button>
            </div>
          </template>
          <template slot-scope="{ row }"
                    slot="operation">
            <div class="flex">
              <cus-button type="text"
                          size="small"
                          :disabled="isjiezhuan!=0"
                          :style="isjiezhuan!=0?'pointer-events: none;opacity: 0.2;color:#1E6FFF;padding:0 8px;':'color:#1E6FFF;padding:0 8px;' "
                          @onClick="addZNCertificateByAccountBookIdApi(row)">
                <Icon type="ios-bookmarks-outline"
                      style="font-size: 15px;"></Icon>入账
              </cus-button>
            </div>
          </template>
        </cusTable>
        <div style="width: 100%; display: flex; justify-content: flex-end">
          <cus-page :data="pages" 
                    @pageChange="queryZdrzApi()"></cus-page>
        </div>
      </div>
    </cus-allcard>

    <cus-modal ref="selectModal"
               title="备注"
               :mask-closable='true'>
     <div v-html="remark">
      
     </div>
      <template slot="footer">
        <div style="display:flex;justify-content: flex-end;">
          <cus-button type="primary"
                      size="small"
                      @onClick="selectModelOk()">确认</cus-button>
        </div>

      </template>
    </cus-modal>
  </div>
</template>
<script>
import {
  getAccountBookByUserId,
  queryZdrz,
  addZNCertificateByAccountBookId
} from '@/api/businessAccountingApi/essentialInformationApi'
export default {
  data () {
    return {
      form: {
        loading: false,
        name: '',
        startTime: '',
        endTime: ''
      },
      // 表头
      columns: [
        {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
        {
          title: '序号',
          type: 'index',
          align: 'center',
          minWidth: 60,
        },
        {
          title: '记账方式',
          key: 'accountways',
          align: 'center',
          minWidth: 70,
        },
        {
          title: '发生时间',
          slot: 'createtime',
          align: 'center',
          minWidth: 80,
        },
        {
          title: '摘要',
          key: 'abstractname',
          align: 'center',
          minWidth: 120,
        },
        {
          title: '金额',
          slot: 'money',
          align: 'right',
          minWidth: 100,
        },
        {
          title: '备注',
          slot: 'operationBz',
          align: 'center',
          minWidth: 70,
        },
        // {
        //   title: '原始凭证',
        //   slot: 'operationYspz',
        //   align: 'center',
        //   minWidth: 70,
        // },
        {
          title: '操作',
          fixed: 'right', // 右侧固定
          slot: 'operation',
          align: 'center',
          minWidth: 70
        }
      ],
      dataList: [], // 表格列表
      // 分页
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      // 选中的表格列表
      selectDataList: [],
      yearList: [], // 账薄年度列表
      accountbookId: null,//账簿id
      isjiezhuan: null,
      remark: '',//备注查看弹框 - 备注信息
      tableHeight: 0
    }
  },
  mounted () {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 64 - 40 - 40 - 24 - 24 - 50 // 表格自适应高度
    }, 100)
    window.addEventListener('resize', this.tableHeightChange, true)
    this.getAccountBookByUserIdApi()  // 根据用户id查询账簿 接口
    this.queryZdrzApi()// 根据用户id查询账簿 接口
  },
  // 消耗时关闭监听
  destroyed () {
    window.removeEventListener('resize', this.tableHeightChange, true)
  },
  methods: {
    // 千位分割符
    totalPrices (recmoney) {
      const intPart = Math.trunc(recmoney)//整数部分
      let floatPart = 0
      const intPartFormat = intPart.toString().replace(/\B(?=(\d{3})+$)/g, ',')
      const valuArray = Number(recmoney).toString().split('.')

      if (valuArray.length === 2) {//有小数部分
        if (valuArray[1]) {
          if (valuArray[1].length === 1) {
            valuArray[1] += '0'
          }
        } else {
          valuArray[1] = '00'
        }
        floatPart = valuArray[1]//取得小数部分

        return intPartFormat + '.' + floatPart
      } else {
        return intPartFormat + '.00'
      }
    },
    tableHeightChange () {
      this.tableHeight = 0
      setTimeout(() => {
        this.tableHeight = window.innerHeight - 64 - 40 - 40 - 24 - 24 - 50 // 表格自适应高度
      }, 100)
    },
    // 勾选记账列表
    selectionChange(e) {
      // 选中改变对应页的选中列
      this.selectDataList[this.pages.page - 1] = e
      console.log(this.selectDataList);
    },
    // 批量入账
    batchAccounting() {
      if(this.selectDataList.length) {
        this.addZNCertificateByAccountBookIdApi()
      }else {
        this.$Message.warning('请选择需要入账列表')
      }
     
    },
    // 根据用户id查询账簿 接口
    getAccountBookByUserIdApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        getAccountBookByUserId({
          userid: this.vuex_user.base.id // 用户id
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.accountbookId = res.basAccountbookList[0].accountbookId
            if (res.basAccountbookList) {
              res.basAccountbookList.forEach(element => {
                if (element.isjiezhuan == 0) {
                  this.isjiezhuan = 0
                }
              })
            }
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 查询自动记账 接口
    queryZdrzApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        queryZdrz({
          status: 0,
          current: this.pages.page,
          size: this.pages.pageSize
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.dataList = res.data
            this.pages.pageTotal = res.totalSize
            for (let i = 0; i < this.dataList.length; i++) {
              if (this.dataList[i].accountway == "1") {
                this.dataList[i].accountways = "入库"
              }
              if (this.dataList[i].accountway == "2") {
                this.dataList[i].accountways = "出库"
              }
              if (this.dataList[i].accountway == "3") {
                this.dataList[i].accountways = "盘盈"
              }
              if (this.dataList[i].accountway == "4") {
                this.dataList[i].accountways = "交伙"
              }
              if (this.dataList[i].accountway == "5") {
                this.dataList[i].accountways = "退伙"
              }
              if (this.dataList[i].accountway == "6") {
                this.dataList[i].accountways = "盘亏"
              }
              console.log(this.selectDataList);
              // 判断选中列表中对应列是否有这调选项
              if(this.selectDataList[this.pages.page - 1]) {
                this.selectDataList[this.pages.page - 1].forEach(item => {
                console.log(item.id);
                // 如果有就默认选中
                if(item.id == this.dataList[i].id) this.dataList[i]._checked = true 
              })
              }
        
            }
            console.log(this.dataList);
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 账簿年度改变回调
    accountbookIdChange () {
      this.pages.page = 1
      this.selectForm.yearList.forEach(element => {
        if (element.accountbookId === this.selectForm.accountbookId) {
          this.selectForm.year = element.year
          this.selectForm.isjiezhuan = element.isjiezhuan
          if (this.selectForm.year == new Date().Format('yyyy')) {
            this.selectForm.starttime = new Date().Format('yyyy') + '-01-01' // 起始日期
            this.selectForm.endtime = new Date().Format('yyyy-MM-dd') // 截止日期
          } else {
            this.selectForm.starttime = this.selectForm.year + '-01-01' // 起始日期
            this.selectForm.endtime = this.selectForm.year + '-12-31' // 截止日期
          }
          this.optionDate() // 限制日期封装方法
        }
      })
      this.queryJFAccountApi()
    },
    // 自动记账入账 接口
    addZNCertificateByAccountBookIdApi (valueData) {
      // 被选择的list
      let selectList =  this.selectDataList.flat()
      // 后端需要改变的格式
      let smartAccountDtoList = []
      // 根据valueData是否有值判断是否为批量入账
      if(valueData) {
         smartAccountDtoList = [{
        sceneFlag: valueData.accountway, //1入库, 2出库,3盘点,4交伙,5退伙	
        moneyOrWeight: valueData.money, //金额或重量	
        jflmFlag: valueData.jflmflag, //经费粮秣标识(0经费1粮秣)	
        staplecertypename: valueData.staplecertypename, //原料名称(经费为null,粮秣写名称)
        id: valueData.id,
      }]
      } else {
        selectList.forEach(item => {
          smartAccountDtoList.push({
            sceneFlag: item.accountway, //1入库, 2出库,3盘点,4交伙,5退伙	
        moneyOrWeight: item.money, //金额或重量	
        jflmFlag: item.jflmflag, //经费粮秣标识(0经费1粮秣)	
        staplecertypename: item.staplecertypename, //原料名称(经费为null,粮秣写名称)
        id: item.id,
      }
          )
        })
      }

      this.form.loading = true
      return new Promise((resolve) => {
        addZNCertificateByAccountBookId({
          accountBookId: this.accountbookId,// 账簿id
          //  department: //单位	
          operatorId: this.vuex_user.base.id, // 用户id
          operatorname: this.vuex_user.base.name,// 用户名
          // billno: valueData.billno, // 账单编号	
          isznjzflag: 1, //智能记账标识(固定传1)
          
          smartAccountDtoList: smartAccountDtoList
        }).then((res) => {
          this.form.loading = false
          if (res.retCode === 0) {
            if(valueData) {
            if  (this.dataList.length == 1 && this.pages.page > 1) this.pages.page--
             this.queryZdrzApi()
            }else { 
              console.log('选择的数组',JSON.stringify(selectList).indexOf(JSON.stringify(this.dataList)));
              // （将数组变为json字符串，再判断是否包含整页数据）判断有没有删除当前页的整页列表数据，让数据倒退
              if(JSON.stringify(selectList).indexOf(JSON.stringify(this.dataList)) != -1 && this.pages.page > 1) this.pages.page--
              this.selectDataList = []
              this.queryZdrzApi()
            }
            this.$Message.success(res.retMsg)
            resolve()
          } else {
            this.$Message.error(res.retMsg)
          }
        })
      })
    },
    // 备注查看弹框的开关
    selectModelChange (remark) {
      this.$refs['selectModal'].show = !this.$refs['selectModal'].show
      this.remark = remark

    },
    // 备注查看弹框的确认按钮
    selectModelOk () {
      this.$refs['selectModal'].show = false
    }
  }
}
</script>
<style lang="less" scoped>
.topBody {
  display: flex;
  padding-top: 24px;
  align-items: center;
  flex-wrap: wrap;
  .topBodyItem {
    margin-right: 12px;
    margin-bottom: 14px;
    .itemSpan {
      white-space: nowrap;
    }
    .itemImport {
      width: 200px;
    }
  }
}
</style>
